package com.think.common.enums.converter;

import cn.hutool.core.convert.Convert;
import com.think.common.enums.IEnum;
import com.think.common.utils.SysUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * <p>
 * 枚举工厂转换类 - String
 * </p>
 *
 * @author: xwj
 * @data: 2019-04-21
 */
public class StringEnumConverterFactory implements ConverterFactory<String, IEnum> {
    private static final Map<Class, Converter> converterMap = new WeakHashMap<>();

    @Override
    public <T extends IEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter result = converterMap.get(targetType);
        if (SysUtils.isEmpty(result)) {
            result = new IntegerStrToEnum<>(targetType);
            converterMap.put(targetType, result);
        }
        return result;
    }

    class IntegerStrToEnum<T extends IEnum> implements Converter<String, T> {

        private final Map<String, T> enumMap = new HashMap<>();

        public IntegerStrToEnum(Class<T> enumType) {
            T[] enums = enumType.getEnumConstants();
            for (T e : enums) {
                enumMap.put(Convert.toStr(e.getValue()), e);
            }
        }

        @Override
        public T convert(String source) {
            T result = enumMap.get(source);
            if (SysUtils.isEmpty(result)) {
                throw new IllegalArgumentException("No element matches " + source);
            }
            return result;
        }
    }
}
